'''
项目入口
'''

from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError

from app.core.BaseResponse import UnicornException
from app.core.errors.http_error import http_error_handler, unicorn_exception_handler
from app.core.errors.validation_error import http422_error_handler
from app.core.events import create_stop_app_handler, create_start_app_handler
from app.core.logging import init_logging
from app.db.database import database_init_db
from app.lib.qiniu import QBox
from app.middleware.Middle import init_middlewares
from app.router import router as api_router
from app.settings.config import API_PREFIX, PROJECT_NAME, DEBUG, VERSION, QINIU_ACCESS_KEY, QINIU_SECRET_KEY


def get_application() -> FastAPI:
    # init_logging()
    application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION)
    # 添加事件
    application.add_event_handler("startup", create_start_app_handler(application))
    application.add_event_handler("shutdown", create_stop_app_handler(application))

    # 添加错误处理
    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError, http422_error_handler)
    application.add_exception_handler(UnicornException, unicorn_exception_handler)

    database_init_db(application)
    init_middlewares(application)
    application.qiniu = QBox({'access_key': QINIU_ACCESS_KEY, 'secret_key': QINIU_SECRET_KEY})
    # 添加路由
    application.include_router(api_router, prefix=API_PREFIX)  # API_PREFIX  “/api"
    return application


app = get_application()
